﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Infrastructure.Diagnostics;

using Infrastructure.ServicesManager;
using TempEmployees.DAL;
using TempEmployees.BLL.Database;
using TempEmployees.BLL.UserAccess;

namespace TempEmployees.BLL.Diagnostics
{
    public static class DatabaseLogger
    {
        static DatabaseLogger()
        {
            Logger.Log += new EventHandler<LoggerEventArgs>(LoggerEventHandler);
        }

        private static void LoggerEventHandler(object sender, LoggerEventArgs e)
        {
            LogEntry entry = new LogEntry();
            entry.Severity = (int)e.Severity;
            entry.Date = e.Date;
            entry.Caller = e.Caller;
            entry.SessionID = e.SessionID;
            entry.Message = e.Message;

            IUserDetails details = null;
            IUserDetailsService service = ServiceEngineSingleton.Instance.GetService<IUserDetailsService>("UserDetailsService");
            if (service != null && (details = service.GetCurrentUser()) != null) entry.UserID = details.ID;

            using (TempEmpDatabaseDataContext db = DbQuery.Database)
            {
                db.LogEntries.InsertOnSubmit(entry);
                db.SubmitChanges();
            }
        }

        public static void Start() { }
    }
}